package be.scond.cartpool;

import java.io.IOException;
import javax.servlet.http.*;
import be.scond.cartpool.API.GroupApi;
import be.scond.cartpool.API.UserApi;
import be.scond.cartpool.exceptions.GroupDoesNotExistException;
import be.scond.cartpool.exceptions.UserNotFoundException;
import be.scond.cartpool.exceptions.WrongPasswordException;

public class LoginServlet extends HttpServlet {
	
	static final long serialVersionUID = 1;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/xml");
		
		String groupName = req.getParameter("groupName");
		String email = req.getParameter("email");
		String password = req.getParameter("password");	
		
		String respons = "<data>";	
		
		try {
			UserApi.login(email, groupName, password);				
			String groupInfoXml = GroupApi.getGroupInfo(groupName);					
			respons += "<succes>Succesfully logged in</succes>";	
			respons += groupInfoXml;
		} catch (UserNotFoundException e) {
			respons += "<error>combination of user with email: "+email+" and group "+groupName+" was not found</error>";	
		} catch (GroupDoesNotExistException e) {
			respons += "<error>"+groupName+" was not found</error>";
		} catch (WrongPasswordException e) {
			respons += "<error>password for "+email+" is wrong, try again.</error>";
		}
		respons += "</data>";

		resp.getWriter().print(respons);
	}
}